from user import models
from django import forms
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
from user.utils.bootstrap import BootStrapModelForm, BootStrapForm


class SigninForm(BootStrapForm):
    username = forms.CharField(
        label='用户名',
        widget=forms.TextInput,
        required=True  # 必填
    )
    password = forms.CharField(
        label='密码',
        widget=forms.PasswordInput(render_value=True),  # 用户名或密码输入错误后在框中保留第一次输入的密码
        required=True
    )


class SignupModelForm(BootStrapModelForm):
    email = forms.CharField(
        label="邮箱",
        validators=[RegexValidator(r'^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$', '邮箱格式错误'), ]
    )
    confirm_password = forms.CharField(
        label="确认密码",
        widget=forms.PasswordInput(render_value=True)
    )

    class Meta:
        model = models.User
        fields = ['username', 'gender', 'email', 'password', 'confirm_password']
        widgets = {
            'password': forms.PasswordInput(render_value=True)
        }

    def clean_confirm_password(self):
        pwd = self.cleaned_data.get('password')
        confirm = self.cleaned_data.get('confirm_password')
        if confirm != pwd:
            raise ValidationError("密码不一致")
        return confirm
